<template>
  <el-dialog title="" :visible.sync="visible" width="533px" :before-close="handleClose">
    <div slot="title" class="title">选择附件简历解析成在线简历</div>
    <div class="tips">
      <i class="el-icon-warning" style="color: #4880ff; margin-right: 8px"></i>
      只可导入
      <span class="red"> 3 </span> 个附件简历文件，若想换文件，请先删除旧文件
    </div>
    <div class="operateBar">
      <span class="text">只支持通过word、pdf文件简历解析</span>
      <span class="btn" @click="uploadResume">新增</span>
    </div>
    <div class="resume-list">
      <div style="height: 100%" v-if="resumeList.length">
        <div class="resume-list-item" v-for="item in resumeList" :key="item.id" @click="handleSelect(item)">
          <img :src="item.checked ? selected : notSelect" class="selectIcon" alt="" />
          <div class="resume-list-item-inner">
            <img :src="resumeIcon" class="resumeIcon" alt="简历" />
            <div class="resume-name">
              <div class="name" :title="item.attName">
                {{ item.attName }}
              </div>
              <div class="time">{{ item.createTime }} 上传</div>
            </div>
            <div class="btn" @click.stop="handleDelete(item)">删除</div>
          </div>
        </div>
      </div>
      <el-empty class="empty" description="暂无简历附件" v-else></el-empty>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="handleClose">关闭</el-button>
      <el-button size="small" type="primary" @click="handleResumeParse">确 定</el-button>
    </span>
    <FullLoading v-if="showFullLoading"></FullLoading>
  </el-dialog>
</template>

<script>
import {
  attachmentList,
  updateResumeName,
  removeResume,
  addResume,
  analysisResult,
  dealAnalysisResume,
} from "@/api/mine";
import resumeIcon from "@/assets/images/png/resumeIcon.png";
import selected from "@/assets/images/png/selected.png";
import notSelect from "@/assets/images/png/notSelect.png";
export default {
  components: {
    FullLoading: () => import("@/components/FullLoading"),
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
  },
  watch: {
    visible(val) {
      if (val) {
        this.attachmentListFn();
      }
    },
  },
  data() {
    return {
      resumeIcon,
      selected,
      notSelect,
      resumeList: [],
      showFullLoading: false,
      currentFile: null,
      MAX_RETRY_TIMES: 10,
      retryCount: 0,
      resumeHasAnalysis: false,
      timer: null,
      personId: localStorage.getItem("personId"),
    };
  },
  mounted() {
    this.$bus.$on("resumeUploadSuccess", this.attachmentListFn);
  },
  beforeMount() {
    this.$bus.$off("resumeUploadSuccess");
  },
  methods: {
    async attachmentListFn() {
      const params = {
        personId: this.personId,
        attStatus: "1",
      };
      const res = await attachmentList(params);
      if (res.code === 200) {
        res.data.forEach((item) => {
          item.checked = false;
        });
        this.resumeList = res.data;
      }
    },
    beforeUpload(files) {
      this.fileName = files.name;
      if (
        [
          "application/pdf",
          "application/vnd.openxmlformats-officedocument.presentationml.presentation",
          "application/msword",
          "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
          "application/vnd.ms-powerpoint",
        ].indexOf(files.type) == -1
      ) {
        this.$message.error("请上传正确的文本格式文件，如pdf doc docx");
        return false;
      }
    },
    async handleUploadSuccess(data) {
      console.log(data);
      const fileUrl = data.data[0];
      const params = {
        personId: this.personId,
        attName: this.fileName,
        attUrl: fileUrl,
      };
      const res = await addResume(params);
      if (res.code === 200) {
        this.$message.success("简历添加成功");
        this.attachmentListFn();
      }
    },
    uploadResume() {
      if (this.resumeList.length >= 3) {
        this.$message.warning(
          "只可以导入3最多个附件简历文件，若想换文件，请先删除旧文件"
        );
        return;
      }
      this.$bus.$emit("uploadResume");
    },
    // 简历在线解析
    async handleResumeParse() {
      if (!this.currentFile) {
        this.$message.warning("请先选择需要解析的简历");
        return;
      }
      this.$confirm("使用简历解析会覆盖原有简历，是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }).then(async () => {
        this.showFullLoading = true;
        const params = {
          personId: this.personId,
          fileUrl: this.currentFile.attUrl, // TODO:
        };
        const res = await dealAnalysisResume(params);
        if (res.code == 200) {
          setTimeout(() => {
            this.startRequest();
          }, 1000);
        } else {
          this.showFullLoading = false;
          this.$message.error("简历解析失败，请稍后再试");
        }
      });
    },
    // 获取附件简历解析结果状态
    async analysisResultFn() {
      try {
        const res = await analysisResult({
          personId: this.personId,
          fileUrl: this.currentFile.attUrl,
          retryNum: this.retryCount + 1,
        });
        if (res.code === 200) {
          const status = res.data;
          if (status == 0) {
            this.$message.error("没有要解析的简历");
            this.endRequest();
          } else if (status == 1) {
            this.showFullLoading = true; // 显示全屏loading，这句不要也行
          } else if (status == 2) {
            this.$message.error("简历解析失败，请重试");
            this.endRequest();
          } else if (status == 3) {
            this.resumeHasAnalysis = true;
            this.endRequest();
            this.$message.success("简历解析成功");
            this.$emit("update:visible", false);
            this.$emit("reqGetResumeData");
          } else {
            this.$message.error("未知错误");
            this.endRequest();
          }
        } else {
          this.endRequest();
          this.$message.error(res.status_desc);
        }
      } catch (err) {
        this.endRequest();
        this.$message.error(err.status_desc);
      }

      // 每次尝试后增加重试计数
      this.retryCount++;

      // 如果超过最大重试次数且仍然未解析完成
      if (!this.resumeHasAnalysis && this.retryCount >= this.MAX_RETRY_TIMES) {
        this.$message.error(
          "超过最大重试次数，简历仍在解析中，请稍后重新进来此页面"
        );
        this.endRequest();
      }
    },
    startRequest() {
      this.timer = setInterval(() => {
        if (this.retryCount < this.MAX_RETRY_TIMES) {
          this.analysisResultFn();
        } else {
          clearInterval(this.timer);
        }
      }, 5000);
    },
    endRequest() {
      clearInterval(this.timer);
      this.retryCount = 0;
      this.showFullLoading = false;
      this.timer = null;
    },
    handleDelete(item) {
      this.$confirm("确定删除此简历?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const params = {
            id: item.id,
            attStatus: "2",
          };
          const res = await removeResume(params);
          if (res.code === 200) {
            this.$bus.$emit("refreshResumeList");
            this.attachmentListFn();
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          }
        })
        .catch(() => {});
    },
    handleSelect(item) {
      this.currentFile = item;
      this.resumeList.forEach((_item) => {
        if (item.id !== _item.id) {
          _item.checked = false;
        } else {
          _item.checked = true;
        }
      });
    },
    handleClose() {
      this.currentFile = null;
      this.$emit("update:visible", false);
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
  padding: 17px 24px;
}
::v-deep .el-dialog__headerbtn {
  top: 17px;
}
::v-deep .el-dialog__body {
  padding: 0;
  border-top: 1px solid #ececec;
  border-bottom: 1px solid #ececec;
}
::v-deep .el-dialog__footer {
  padding: 20px;
}
::v-deep .el-empty__image {
  width: 90px;
}
.title {
  font-family: MicrosoftYaHei;
  font-size: 16px;
  color: rgba(0, 0, 0, 0.85);
}
.tips {
  display: flex;
  align-items: center;
  font-family: PingFangSC, PingFang SC;
  font-size: 14px;
  color: #666666;
  padding: 10px 24px;
  background: #e6f7ff;
  .red {
    color: #ff6738;
    margin: 0 3px;
  }
}
.operateBar {
  display: flex;
  align-items: center;
  padding: 12px 24px 22px 40px;
  .text {
    font-family: MicrosoftYaHei;
    font-size: 14px;
    color: rgba(0, 0, 0, 0.85);
  }
  .btn {
    font-family: MicrosoftYaHei;
    font-size: 14px;
    color: #4880ff;
    margin-left: 10px;
    cursor: pointer;
  }
}
.resume-list {
  max-height: 260px;
  padding: 0 24px 15px 40px;
  &-item {
    display: flex;
    align-items: center;
    cursor: pointer;
    margin-bottom: 10px;
    &-inner {
      display: flex;
      align-items: center;
      padding: 15px 14px;
      border: 1px solid #dfdfdf;
      border-radius: 4px;
      flex: 1;
    }
    &:last-child {
      margin-bottom: 0;
    }
    .selectIcon {
      width: 24px;
      height: 24px;
      margin-right: 11px;
      cursor: pointer;
    }
    .resumeIcon {
      width: 34px;
      height: 34px;
      margin-right: 13px;
    }
    .resume-name {
      .name {
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 14px;
        color: #222222;
        margin-bottom: 5px;
        width: 300px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
    .time {
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 12px;
      color: #bfbfbf;
    }
    .btn {
      color: #4880ff;
      cursor: pointer;
      margin-left: auto;
    }
  }
}
</style>
